﻿using ST.Torch.WebApi.Application.Utils.Dtos;
using ST.Torch.WebApi.Application.Utils;
using ST.Torch.WebApi.Core.Entities.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Furion.Localization;
using ST.Torch.WebApi.Application.System.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

namespace ST.Torch.WebApi.Application.WebSize
{
    /// <summary>
    /// Jwt 接口
    /// </summary>
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class WebSiteAppService : IDynamicApiController
    {
        //前端Headers Authorization:Bearer  
        public string appid = "wxe406fe2d200cd668";
        public string appsecret = "74e01414082b904019c890baae84a9b3";
        private readonly ISYSUserService _SYSUserService;
        private readonly IUIDService _UIDService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SYSUserService"></param>
        /// <param name="UIDService"></param>
        /// <param name="httpContextAccessor"></param>
        public WebSiteAppService(ISYSUserService SYSUserService, IUIDService UIDService, IHttpContextAccessor httpContextAccessor)
        {
            
            _SYSUserService = SYSUserService;
            _UIDService = UIDService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="Account">账号</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<dynamic> Login([FromForm] string Account, [FromForm] string Password)
        {
            try
            {
                string ErrorMsg = "";
                var userInfo = await _SYSUserService.SingleAsync(u => u.Account == Account);
                if (userInfo == null)
                {
                    ErrorMsg = ($" {L.Text["账号不存在"]}");
                    return new { code = 500, Errors = ErrorMsg };

                }
                else
                {
                    if (userInfo.Password != userInfo.GetPassEncryption(Password))
                    {
                        ErrorMsg = ($" {L.Text["密码错误"]}");
                        return new { code = 500, Errors = ErrorMsg };

                    }
                    // 生成 token
                    string accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                    {
                       { "UserId",userInfo.Id }

                    });

                    //创建用户身份标识
                    var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    claimsIdentity.AddClaims(new List<Claim>()
                    {
                        new Claim("UserId", userInfo.Id.ToString()),

                    });
                   
                    // 设置Swagger自动登录
                    _httpContextAccessor.HttpContext.SigninToSwagger(accessToken);
                    // 获取刷新 token
                    var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 43200); // 第二个参数是刷新 token 的有效期（分钟），默认三十天
                    _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
                    _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
                    //return RedirectToAction("Index", "Home");
                    return new { code = 200, UserId = userInfo.Id, accessToken = accessToken,refreshToken= refreshToken };


                }


            }
            catch (Exception e)
            {
                //throw Oops.Oh($"" + e.Message);
                return new { code = 500, Errors = e.Message };

            }
            //return View();

        }


        [HttpPost]
        public async Task<string> Test()
        {
           
            return  await Task.FromResult("TT");  
        }

    }
}
